package com.hfzy.ihk.web.callhistoryold.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.common.core.elasticsearch.EsQueryUtils;
import com.hfzy.ihk.common.core.elasticsearch.service.EsBaseServiceImpl;
import com.hfzy.ihk.common.util.date.DateUtils;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.facade.callhistoryold.request.CallHistoryOldRequest;
import com.hfzy.ihk.facade.callhistoryold.request.CallHistoryZy4ListRequest;
import com.hfzy.ihk.facade.callhistoryold.request.ClickUserRequest;
import com.hfzy.ihk.web.callhistoryold.client.CallHistoryCrmRmiService;
import com.hfzy.ihk.web.callhistoryold.dao.CallHistoryOldRepository;
import com.hfzy.ihk.web.callhistoryold.entity.CallHistoryOld;
import com.hfzy.ihk.web.callhistoryold.entity.CallhistoryPlayRecord;
import com.hfzy.ihk.web.callhistoryold.entity.ClickUser;
import com.hfzy.ihk.web.callhistoryold.entity.PhoneData;
import com.hfzy.ihk.web.callhistoryold.enumType.CallChannel;
import com.hfzy.ihk.web.callhistoryold.enumType.CallFromType;
import com.hfzy.ihk.web.callhistoryold.enumType.PageFromType;
import com.hfzy.ihk.web.callhistoryold.rmi.client.CallHistoryLcRmiService;
import com.hfzy.ihk.web.callhistoryold.task.CallHistoryCrmRunnable;
import com.hfzy.ihk.web.callhistoryold.utils.kafka.KafkaUtil;
import com.hfzy.ihk.web.callhistoryold.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class CallHistoryOldBiz extends EsBaseServiceImpl<CallHistoryOld> {

    @Autowired
    CallHistoryOldRepository callHistoryOldRepository;

    @Autowired
    PhoneDataBiz phoneDataBiz;

    @Autowired
    CallHistoryLcRmiService callHistoryLcRmiService;

    @Autowired
    CallhistoryPlayRecordBiz callhistoryPlayRecordBiz;

    private static CallHistoryCrmRmiService callHistoryCrmRmiService;

    @Resource
    public void setCallHistoryCrmRmiService(CallHistoryCrmRmiService callHistoryCrmRmiService) {
        this.callHistoryCrmRmiService = callHistoryCrmRmiService;
    }

    @Override
    protected ElasticsearchCrudRepository getReposity() {
        return callHistoryOldRepository;
    }

    public List<CallHistoryOld> getDatasFromHBaseByUserId(int userId, int limit,String startRowKey) {

        List<CallHistoryOld> callHistoryList = new ArrayList<>();

        String callHistoryStr = callHistoryLcRmiService.getCallHistorysByCreateUserId(userId, limit, startRowKey);
        JSONArray callHistoryJArr = JSONArray.parseArray(callHistoryStr);

        for (int j = 0; j < callHistoryJArr.size(); j++) {
            JSONObject callHistoryJObj = callHistoryJArr.getJSONObject(j);
            if (callHistoryJObj != null) {
                CallHistoryOldVo callHistoryOldVo = JSONObject.parseObject(callHistoryJObj.toString(), CallHistoryOldVo.class);
                setItem(callHistoryOldVo, false);
                CallHistoryOld callHistory = new CallHistoryOld();
                BeanUtils.copyProperties(callHistoryOldVo, callHistory);
                callHistoryList.add(callHistory);
            }
        }
        return callHistoryList;
    }



    public void buildDatasFromHBase(int startUserId, int limit){

        String userIdStr = callHistoryLcRmiService.getCreateUserIdAsc(startUserId,limit);
        JSONArray userIdJArr = JSONArray.parseArray(userIdStr);

        for(int i=0;i<userIdJArr.size();i++){
            JSONObject uIdJObject = userIdJArr.getJSONObject(i);
            List<CallHistoryOld> callHistoryList = new ArrayList<>();
            if(uIdJObject != null){
                CallHistoryOldVo uIdObj = JSONObject.parseObject(uIdJObject.toString(),CallHistoryOldVo.class);
                Integer userId = uIdObj.getCreateUserId();
                JSONArray callHistoryJArr = null;
                String startRowKey = null;
                do {
                    String callHistoryStr = callHistoryLcRmiService.getCallHistorysByCreateUserId(userId, limit, startRowKey);
                    callHistoryJArr = JSONArray.parseArray(callHistoryStr);
                    for (int j = 0; j < callHistoryJArr.size(); j++) {
                        JSONObject callHistoryJObj = callHistoryJArr.getJSONObject(j);
                        if (callHistoryJObj != null) {
                            CallHistoryOldVo callHistoryOldVo = JSONObject.parseObject(callHistoryJObj.toString(), CallHistoryOldVo.class);
                            startRowKey = callHistoryOldVo.getPK();
                            setItem(callHistoryOldVo,false);

                            CallHistoryOld callHistory = new CallHistoryOld();
                            BeanUtils.copyProperties(callHistoryOldVo,callHistory);
                            callHistoryList.add(callHistory);
                        }
                    }
                }while (callHistoryJArr.size() >= limit);
            }
            if(callHistoryList.size() > 0){
                insertBatch(callHistoryList,limit);
            }
        }

    }

    public void saveDatas(List<CallHistoryOldVo> dataList) {

        for (int i = 0; i < dataList.size(); i ++) {

            CallHistoryOldVo callHistoryOldVo = dataList.get(i);
            setItem(callHistoryOldVo,true);

            CallHistoryOld callHistoryOld = new CallHistoryOld();
            BeanUtils.copyProperties(callHistoryOldVo,callHistoryOld);

            if(callHistoryOldRepository.existsById(callHistoryOld.getId())) {
                callHistoryOldRepository.updateSomeFieldsOnlyNotNull(callHistoryOld);
            }else {
                insert(callHistoryOld);
            }

        }
        log.info("完成 === saveDatas === CallHistoryOld 云呼数据 === 批量处理数据,size:" + dataList.size());
    }

    private void setItem(CallHistoryOldVo callHistory,boolean isFromYunhu) {
        //推送kafka数据
        Map kafkaMap = new HashMap();

        kafkaMap.put("sessionId", callHistory.getPK());
        kafkaMap.put("mainCallLength", "0");
        kafkaMap.put("targetCallLength", "0");
        kafkaMap.put("mainChargedDuration", "0");
        kafkaMap.put("targetChargedDuration", "0");
        kafkaMap.put("mainCallIsLongDistance", "false");
        kafkaMap.put("targetCallIsLongDistance", "false");

        //运营商类型(东进(0)/电信(1)，手机（2）(在线),手机离线(3),(9)阿里云)
        kafkaMap.put("commitTo", "-1");
        //通话类型(呼出(0)、呼入(1),呼出《经纪人呼主显转接到客户》(2))
        kafkaMap.put("callType", "-1");
        //被叫应答
        kafkaMap.put("targetCallAnswered", "false");
        //主叫应答
        kafkaMap.put("mainCallAnswered", "false");


        if(!isFromYunhu) {
            callHistory.setId(callHistory.getPK());
            callHistory.setSessionId(callHistory.getPK());
        }else {
            callHistory.setId(callHistory.getSessionId());
        }


        if (callHistory.getCreateTime() == null) {
            callHistory.setCreateTime(callHistory.getDialTime());
        }
        //绑定云呼来源ID
        if (callHistory.getCallFromId() != null) {//判断置业来源ID
            callHistory.setObjectId(callHistory.getCallFromId().toString());
        } else if (!StringTools.isEmpty(callHistory.getPropertyNo()) && callHistory.getPageFrom() != null && (callHistory.getPageFrom() == 0 || callHistory.getPageFrom() == 2)) {//查询盘源ID
            //从数据库查的接口
            Long id= callHistoryLcRmiService.getPropertyIdByPropertyNo(callHistory.getPropertyNo());
            if (id != null) {
                callHistory.setObjectId(id.toString());
            }
        } else if (!StringTools.isEmpty(callHistory.getPropertyNo()) && callHistory.getPageFrom() != null && (callHistory.getPageFrom() == 4 || callHistory.getPageFrom() == 7)) {//查询客户ID
            //从数据库查的接口
            if(isFromYunhu){
                //这里是云呼自己的特殊性，customerNo和propertyNo都用同一个propertyNo字段
                Long id = callHistoryLcRmiService.getCustomerIdByCustomerNo(callHistory.getPropertyNo());
                if (id != null) {
                    callHistory.setObjectId(id.toString());
                }
            }/*else {
                callHistoryLcRmiService.getCustomerIdByCustomerNo(callHistory.getCustomerNo());
            }*/


        }

        if (callHistory.getPageFrom() != null && callHistory.getPageFrom() != -1 && callHistory.getPageFrom() != 6) {//(pageFrom = 6)房专家云呼记录重新细分类型
            callHistory.setPageFrom(callHistory.getPageFrom());
        } else {
            Integer pageFrom = returnPageFrom(callHistory);
            if (pageFrom != null && pageFrom != -1) {
                callHistory.setPageFrom(pageFrom);
            }
        }

        if (StringTools.isNotempty(callHistory.getMainCallPhone())) {
            if (callHistory.getCommitTo() != null && (callHistory.getCommitTo() == 0 || callHistory.getCommitTo() == 9)){
                callHistory.setCustomerPhone(callHistory.getMainCallPhone());
            }
            if (callHistory.getIsPushKafka() != null && callHistory.getIsPushKafka()) {
                String flag = isLongDistance(callHistory.getMainCallPhone());//判断是否长途
                kafkaMap.put("mainCallIsLongDistance", flag);
            }
        }

        if ((callHistory.getMainCallLength() != null)) {

            kafkaMap.put("mainCallLength", callHistory.getMainCallLength().toString());

            if (callHistory.getCommitTo() != null && callHistory.getCommitTo() == 9) {//阿里云
                if (StringTools.isNotempty(callHistory.getCallType()) && callHistory.getCallType().equals("0")) {
                    //主叫计费时长
                    long mainCallFeeTimeLength = callLength(callHistory.getMainCallLength());

                    callHistory.setMainChargedDuration(mainCallFeeTimeLength);

                    kafkaMap.put("mainChargedDuration", String.valueOf(mainCallFeeTimeLength));

                }
            }
        }

        if (callHistory.getTargetCallLength() != null) {//被叫
            if(callHistory.getCommitTo() != null) {
                if (callHistory.getCommitTo() == 0 || callHistory.getCommitTo() == 9) {
                    callHistory.setConnectTimeSecond(callHistory.getTargetCallLength());
                }
            }

            callHistory.setTargetCallLength(callHistory.getTargetCallLength());
            kafkaMap.put("targetCallLength", callHistory.getTargetCallLength().toString());

            if (callHistory.getCommitTo() != null && callHistory.getCommitTo() == 9) {//阿里云

                if (StringTools.isNotempty(callHistory.getCallType()) && (callHistory.getCallType().equals("0") || callHistory.getCallType().equals("1") || callHistory.getCallType().equals("2") || callHistory.getCallType().equals("1"))) {

                    long targetCallFeeTimeLength = callLength(callHistory.getTargetCallLength());
                    callHistory.setTargetChargedDuration(targetCallFeeTimeLength);
                    kafkaMap.put("targetChargedDuration", String.valueOf(targetCallFeeTimeLength));
                }
            }

            setTargetCallLengthCache(callHistory, callHistory.getTargetCallLength());
        }

        if(callHistory.getRecordTimeLength() != null){
            if(callHistory.getCommitTo() != null && (callHistory.getCommitTo() == 2 || callHistory.getCommitTo() == 3)){
                callHistory.setConnectTimeSecond(callHistory.getRecordTimeLength().longValue());
            }
        }

        //云呼1.0计算规则
        if (callHistory.getCommitTo() != null && callHistory.getCommitTo() == 0) {//1.0云呼
            if (callHistory.getCallType().equals("0")) {//主叫时长

                if (callHistory.getDisconnectTime() != null && callHistory.getMainCallAnsweredTime() != null) {
                    //主叫通话时长
                    Long total = (callHistory.getDisconnectTime().getTime() - callHistory.getMainCallAnsweredTime().getTime()) / 1000;
                    callHistory.setMainCallLength(total);

                    //主叫计费时长
                    long mainCallFeeTimeLength = callLength(total);
                    callHistory.setMainChargedDuration(mainCallFeeTimeLength);

                    //主叫通话时长
                    kafkaMap.put("mainCallLength", total.toString());
                    //主叫计费时长
                    kafkaMap.put("mainChargedDuration", String.valueOf(mainCallFeeTimeLength));
                }

                if (callHistory.getDisconnectTime() != null && callHistory.getTargetCallAnsweredTime() != null) {
                    //被叫通话时长
                    Long total1 = (callHistory.getDisconnectTime().getTime() - callHistory.getTargetCallAnsweredTime().getTime()) / 1000;
                    callHistory.setTargetCallLength(total1);

                    long targetCallFeeTimeLength = callLength(total1);
                    callHistory.setTargetChargedDuration(targetCallFeeTimeLength);

                    //被叫通话时长
                    kafkaMap.put("targetCallLength", total1.toString());
                    //被叫计费时长
                    kafkaMap.put("targetChargedDuration", String.valueOf(targetCallFeeTimeLength));

                    setTargetCallLengthCache(callHistory, total1);
                }
            } else if ((callHistory.getCallType().equals("1") || callHistory.getCallType().equals("2"))
                    && callHistory.getDisconnectTime() != null
                    && callHistory.getTargetCallAnsweredTime() != null) { //被叫时长
                //被叫通话时长
                Long total = (callHistory.getDisconnectTime().getTime() - callHistory.getTargetCallAnsweredTime().getTime()) / 1000;
                callHistory.setTargetCallLength(total);

                long targetCallFeeTimeLength = callLength(total);
                callHistory.setTargetChargedDuration(targetCallFeeTimeLength);

                //被叫通话时长
                kafkaMap.put("targetCallLength", total.toString());
                //被叫计费时长
                kafkaMap.put("targetChargedDuration", String.valueOf(targetCallFeeTimeLength));

                setTargetCallLengthCache(callHistory, total);

            }
        } else if (callHistory.getRecordTimeLength() != null && callHistory.getRecordTimeLength() != -1) {//2.0通话时长
            callHistory.setRecordTimeLength(callHistory.getRecordTimeLength());

            //被叫通话时长
            kafkaMap.put("targetCallLength", callHistory.getRecordTimeLength().toString());

            if (
                    ((callHistory.getTargetCallAnswered() != null && callHistory.getTargetCallAnswered()) || (callHistory.getMainCallAnswered() != null && callHistory.getMainCallAnswered())) &&
                            callHistory.getCommitTo() != null && (callHistory.getCommitTo() == 2 || callHistory.getCommitTo() == 3)
                    ) {//2.0云呼(需要判断主叫或者被叫是否接通)
                long targetCallFeeTimeLength = callLength(Long.valueOf(callHistory.getRecordTimeLength()));
                callHistory.setTargetChargedDuration(targetCallFeeTimeLength);

                callHistory.setTargetCallLength(callHistory.getRecordTimeLength().longValue());

                //被叫计费时长
                kafkaMap.put("targetChargedDuration", String.valueOf(targetCallFeeTimeLength));

                setTargetCallLengthCache(callHistory, callHistory.getRecordTimeLength());
            }
        }

        if (StringTools.isNotempty(callHistory.getTargetCallPhone())) {
            if(callHistory.getCommitTo() != null && (callHistory.getCommitTo() == 2 || callHistory.getCommitTo() == 3)){
                callHistory.setCustomerPhone(callHistory.getTargetCallPhone());
            }
            if (callHistory.getIsPushKafka() != null && callHistory.getIsPushKafka()) {
                String flag = isLongDistance(callHistory.getTargetCallPhone());//判断是否长途
                callHistory.setTargetCallIsLongDistance(flag);
                kafkaMap.put("targetCallIsLongDistance", flag);
            }
        }


        if (!StringTools.isEmpty(callHistory.getCommitTo()) && callHistory.getCommitTo() != -1) {
            kafkaMap.put("commitT/", callHistory.getCommitTo().toString());
        }


        if (!StringTools.isEmpty(callHistory.getCallType()) && !callHistory.getCallType().equals("-1")) {
            kafkaMap.put("callType", callHistory.getCallType());
        }

        if (!StringTools.isEmpty(callHistory.getMainCallAnswered())) {

            kafkaMap.put("mainCallAnswered", callHistory.getMainCallAnswered().toString());
        }

        if (!StringTools.isEmpty(callHistory.getTargetCallAnswered())) {

            kafkaMap.put("targetCallAnswered", callHistory.getTargetCallAnswered().toString());
        }

        if (!StringTools.isEmpty(callHistory.getFeedBack())) {
            callHistory.setFailedReason(callHistory.getFeedBack());
        }

        if(isFromYunhu) {
            if (callHistory.getIsPushKafka() != null && callHistory.getIsPushKafka() && (!kafkaMap.get("mainChargedDuration").equals("0") || !kafkaMap.get("targetChargedDuration").equals("0"))) {
                log.info("==================推送时长数据==================={}", kafkaMap);
                KafkaUtil.send("call_length", JSON.toJSONString(kafkaMap));
            }
        }

    }

    public static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(12, 15, 3,
            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000),
            new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    if (!executor.isShutdown()) {
                        try {
                            executor.getQueue().put(r);
                        } catch (InterruptedException e) {
                            // should not be interrupted
                        }
                    }
                }
            });

    //把时长写入缓存
    private static void setTargetCallLengthCache(CallHistoryOldVo callHistoryOldVo, long targetCallLength) {
        try {
//            log.info("开始==>setTargetCallLengthCache");
            if (callHistoryOldVo.getPageFrom() != null && callHistoryOldVo.getPageFrom().intValue() == 55) {
                threadPoolExecutor.execute(new CallHistoryCrmRunnable(callHistoryCrmRmiService, targetCallLength, callHistoryOldVo.getCreateUserId(), callHistoryOldVo.getObjectId()));
            }
//            log.info("结束==>setTargetCallLengthCache");
        } catch (Exception e) {
            log.info("报错==>setTargetCallLengthCache", e);
        }
    }

    //置业云呼来源字段转换
    public static Integer returnPageFrom(CallHistoryOldVo callHistoryOldVo) {
        Integer pageFrom = -1;
        if (!StringTools.isEmpty(callHistoryOldVo.getCallFromType()) && !StringTools.isEmpty(callHistoryOldVo.getCallChannel())) {
            if (callHistoryOldVo.getCallChannel().trim().equals("PC")) {//PC端
                switch (callHistoryOldVo.getCallFromType().trim()) {
                    case "PC":
                        pageFrom = 2;
                        break;
                    case "LC":
                        pageFrom = 3;
                        break;
                    case "CF":
                        pageFrom = 10;
                        break;
                    case "CE":
                        pageFrom = 4;
                        break;
                    case "CEA":
                        pageFrom = 22;
                        break;
                    case "AEP":
                        pageFrom = 33;
                        break;
                    case "ARP":
                        pageFrom = 44;
                        break;
                    case "TAOC":
                        pageFrom = 55;
                        break;
                    case "CH":
                        pageFrom = 66;
                        break;
                    default:
                        pageFrom = -1;
                        break;
                }
            } else { //手机端
                switch (callHistoryOldVo.getCallFromType().trim()) {
                    case "PC":
                        pageFrom = 0;
                        break;
                    case "LC":
                        pageFrom = 1;
                        break;
                    case "APPR":
                        pageFrom = 6;
                        break;
                    case "CE":
                        pageFrom = 7;
                        break;
                    case "APPLC":
                        pageFrom = 8;
                        break;
                    case "APPPC":
                        pageFrom = 9;
                        break;
                    default:
                        pageFrom = -1;
                        break;
                }
            }
        } else {
            pageFrom = callHistoryOldVo.getPageFrom();
        }
        return pageFrom;
    }

    //判断是否长途
    public String isLongDistance(String phone) {
        String flag = "false";

        if (phone.length() < 7 || phone.startsWith("020")) {//非号码
            return flag;
        }

        if (phone.startsWith("0") && !phone.startsWith("020")) {//长途
            flag = "true";
            return flag;
        }

        String p = phone.substring(0, 7);

        List<String> cityList = phoneDataBiz.getPhoneDataByPhoneLike(p);

        if (StringTools.isNotempty(cityList)) {
            String city = cityList.get(0);
            if (!city.equals("广州")) {//非广州
                flag = "true";
                return flag;
            }
        }

        return flag;
    }

    //计算计费时长
    public static Long callLength(Long total) {
        long size = 0;
        long count = total % 60;
        if (count > 0) {
            size = total - count + 60;
        }
        return size;
    }


    public String getCallRecords(Map paramMap) {
        log.info("getCallRecords-> {}", paramMap);

        JSONObject json = new JSONObject();
        try {
            Integer userId = paramMap.get("userId") == null ? -1 : (Integer) paramMap.get("userId");
            String content = paramMap.get("content") == null ? null : paramMap.get("content").toString();
            Integer page = paramMap.get("page") == null ? -1 : (Integer) paramMap.get("page");
            Integer pageSize = paramMap.get("pageSize") == null ? -1 : (Integer) paramMap.get("pageSize");
            Long timestamp = paramMap.get("timestamp") == null ? null : (Long) paramMap.get("timestamp");

            if (userId < 0) {
                throw new IllegalArgumentException("用户不存在");
            }

            CallHistoryOldRequest request = new CallHistoryOldRequest();

            request.setUserId(userId);
            request.setContent(content);
            request.setPage(page-1);
            request.setPageSize(pageSize);

            timestamp = StringTools.generateTimestamp(page, timestamp);
            request.setTimestamp(timestamp);

            Date now = new Date();
            request.setDialTimeEnd(now);
            request.setDialTimeStart(DateUtils.addDay(now, -30));
            request.setCallChannel(CallChannel.FORM_PC.toStr());
            request.setIsDelete("false");
            request.setIsDeleteRecord("false");

            List<CallHistoryOld> resultList = getCallHistoryOld(request);
            List<Map> dataList = new ArrayList<>();

            for (CallHistoryOld item : resultList) {
                Map map = new HashMap();

                map.put("id", item.getId());
                map.put("phone", item.getPhone());
                map.put("ownerName", item.getCustomerName());
                map.put("status", item.getCallType());////呼叫类型（IC:呼入,OC:呼出）
                map.put("callTime", item.getDialTime() != null ? item.getDialTime() : "");

                if (item.getCallFromType() != null)
                    item.setCallFromType(item.getCallFromType().trim());

                map.put("type", item.getCallFromType());

                if (CallFromType.PropertyCallPhone.toStr().equals(item.getCallFromType())) {
                    map.put("propertyNo", !StringTools.isNullString(item.getPropertyNo()) ? "盘编:" + item.getPropertyNo() : "盘编:");//格式：盘编:xxxx,客编:xxxx,""(联动call留空)
                    map.put("address", !StringTools.isNullString(item.getRemark()) ? "物业地址:" + item.getRemark() : "物业地址:");

                } else if (CallFromType.CustomerEbook.toStr().equals(item.getCallFromType())) {
                    map.put("propertyNo", !StringTools.isNullString(item.getCustomerNo()) ? "客编:" + item.getCustomerNo() : "客编:");//格式：盘编:xxxx,客编:xxxx,""(联动call留空)
                    map.put("address", !StringTools.isNullString(item.getRemark()) ? item.getRemark() : "最后跟进:");

                } else if (CallFromType.LinkageCallPhone.toStr().equals(item.getCallFromType())) {
                    map.put("propertyNo", "");//格式：盘编:xxxx,客编:xxxx,""(联动call留空)
                    map.put("address", !StringTools.isNullString(item.getRemark()) ? item.getRemark() : "项目:");

                } else if (CallFromType.TAOCUSTOMER.toStr().equals(item.getCallFromType())) {
                    map.put("propertyNo", !StringTools.isNullString(item.getCustomerNo()) ? "客编:" + item.getCustomerNo() : "客编:");//格式：盘编:xxxx,客编:xxxx,""(联动call留空)
                    map.put("address", !StringTools.isNullString(item.getRemark()) ? item.getRemark() : "最近跟进:");
                } else if (CallFromType.CALLIN.toStr().equals(item.getCallFromType())) {

                    if (!StringTools.isNullString(item.getPropertyNo())) {
                        map.put("propertyNo", !StringTools.isNullString(item.getPropertyNo()) ? "盘编:" + item.getPropertyNo() : "盘编:");
                        map.put("address", !StringTools.isNullString(item.getRemark()) ? "物业地址:" + item.getRemark() : "物业地址:");
                    } else if (!StringTools.isNullString(item.getCustomerNo())) {
                        map.put("propertyNo", !StringTools.isNullString(item.getCustomerNo()) ? "客编:" + item.getCustomerNo() : "客编:");
                        map.put("address", !StringTools.isNullString(item.getRemark()) ? item.getRemark() : "最后跟进:");
                    } else {
                        map.put("propertyNo", item.getPropertyNo());
                        map.put("address", item.getRemark());
                    }
                } else {
                    map.put("propertyNo", item.getPropertyNo());
                    map.put("address", item.getRemark());
                }

                /*客户类型*/
                if (CallFromType.LinkageCallPhone.toStr().equals(item.getCallFromType()) ||
                        CallFromType.ContinueFollow.toStr().equals(item.getCallFromType()) ||
                        CallFromType.CustomerEbook.toStr().equals(item.getCallFromType()))
                    map.put("customerType", "CUSTOMER");
                else if (CallFromType.PropertyCallPhone.toStr().equals(item.getCallFromType()))
                    map.put("customerType", "OWNER");
                else if (CallFromType.CALLIN.toStr().equals(item.getCallFromType()))
                    map.put("customerType", "INCALL");

                dataList.add(map);
            }

            json.put("result", 10000);
            json.put("msg", "成功");

            JSONObject subJson = new JSONObject();
            subJson.put("timestamp", timestamp);
            subJson.put("total", dataList.size());
            subJson.put("list", dataList);

            json.put("data", subJson);

        } catch (IllegalArgumentException e1) {
            log.error("", e1);
            json.put("result", 10008);
            json.put("msg", e1.getMessage());

        } catch (Exception e2) {
            log.error("", e2);
            json.put("result", 10009);
            json.put("msg", "接口异常");

        } finally {
            return json.toString();
        }

    }


    public List<CallHistoryOld> getCallHistoryOld(CallHistoryOldRequest request) {
        List<CallHistoryOld> rsList = new ArrayList<CallHistoryOld>();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();

        if(request.getUserId() != null) {
            //hfit可以看全部，所以不需要做筛选
            if(20358 != request.getUserId().intValue()) {
                bqb.must(EsQueryUtils.termQuery("createUserId", request.getUserId()));
            }
        }

        if(request.getDialTimeStart()!=null || request.getDialTimeEnd()!=null) {
            bqb.must(EsQueryUtils.rangeQuery("createTime", request.getDialTimeStart() != null ? DateUtils.toString(request.getDialTimeStart(), "yyyy-MM-dd HH:mm:ss") : null,
                    request.getDialTimeEnd() != null ? DateUtils.toString(request.getDialTimeEnd(), "yyyy-MM-dd HH:mm:ss") : null, true, true));
        }

        if(StringTools.isNotempty(request.getIsDelete())) {
            bqb.must(EsQueryUtils.termQuery("isDelete", request.getIsDelete()));
        }

        if(StringTools.isNotempty(request.getIsDeleteRecord())) {
            bqb.must(EsQueryUtils.termQuery("isDeleteRecord", request.getIsDeleteRecord()));
        }

        if(StringTools.isNotempty(request.getCallChannel())) {
            bqb.must(EsQueryUtils.termQuery("callChannel", request.getCallChannel()));
        }

        if(StringTools.isNotempty(request.getContent())) {
            BoolQueryBuilder bqb2 = QueryBuilders.boolQuery();
            bqb2.should(EsQueryUtils.wildcardQuery("propertyNo", "*" + request.getContent() + "*"));
            bqb2.should(EsQueryUtils.wildcardQuery("customerName", "*" + request.getContent() + "*"));
            bqb2.should(EsQueryUtils.wildcardQuery("remark", "*" + request.getContent() + "*"));

            bqb.must(bqb2);
        }

        FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder().withQuery(bqb).withSort(fieldSortBuilder).withPageable(PageRequest.of(request.getPage(), request.getPageSize()));
        Page<CallHistoryOld> page = callHistoryOldRepository.search(builder.build());
        Iterator<CallHistoryOld> it = page.iterator();

        while (it.hasNext()) {
            rsList.add(it.next());
        }
        return rsList;
    }

    public List<CallHistoryFzjListVo> getCallhistoryListByCallHistoryFzjConditionVo(CallHistoryFzjConditionVo callHistoryFzjConditionVo) {

        List<CallHistoryFzjListVo> rsList = new ArrayList<CallHistoryFzjListVo>();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        bqb.must(EsQueryUtils.existsQuery("createTime"));
        bqb.mustNot(EsQueryUtils.termQuery("pageFrom", 5));
        bqb.mustNot(EsQueryUtils.termQuery("pageFrom", 55));
        bqb.must(EsQueryUtils.rangeQuery("targetCallLength", 1, null, false, false));
        if (StringTools.isNotempty(callHistoryFzjConditionVo.getEnrollNumber())) {
            bqb.must(EsQueryUtils.termQuery("enrollNumber", callHistoryFzjConditionVo.getEnrollNumber()));
        }


        boolean isAll = false;
        String[] condArr = null;
        if (StringTools.isNotempty(callHistoryFzjConditionVo.getCondition())) {
            condArr = callHistoryFzjConditionVo.getCondition().split(",");
            for (int j = 0; j < condArr.length; j++) {
                if (condArr[j].trim().equals("all")) {
                    isAll = true;
                }
            }
        }

        if (condArr != null) {
            if (!isAll) {
                BoolQueryBuilder bqb2 = QueryBuilders.boolQuery();
                for (int i = 0; i < condArr.length; i++) {
                    String str = condArr[i];
                    switch (str) {
                        case "propertyInspection": //可看楼业主
                            bqb2.should(EsQueryUtils.termQuery("isPushApp", "true"));
                            break;
                        case "customerAccept": //接收邀请客户
                            bqb2.should(EsQueryUtils.termQuery("customerFollowFeedBack", "ACCEPT"));
                            break;
                        case "customerFollowUp"://继续跟进客户
                            bqb2.should(EsQueryUtils.termQuery("customerFollowFeedBack", "FOLLOWUP"));
                            break;
                        case "callin"://呼入记录(回拨)
                            bqb2.should(EsQueryUtils.termQuery("callType", "1"));
                            break;
                        case "customerEbook"://电子客薄
                            bqb2.should(EsQueryUtils.termQuery("pageFrom", 4));
                            bqb2.should(EsQueryUtils.termQuery("pageFrom", 7));
                            break;
                    }
                }
                bqb.must(bqb2);
            }
        }

        if (StringTools.isNotempty(callHistoryFzjConditionVo.getInputText())) {//输入搜索条件
            BoolQueryBuilder bqb3 = QueryBuilders.boolQuery();
            bqb3.should(EsQueryUtils.wildcardQuery("customerName", "*" + callHistoryFzjConditionVo.getInputText() + "*"));
            bqb3.should(EsQueryUtils.wildcardQuery("totalAddress", "*" + callHistoryFzjConditionVo.getInputText() + "*"));
            bqb3.should(EsQueryUtils.wildcardQuery("project", "*" + callHistoryFzjConditionVo.getInputText() + "*"));
            bqb.must(bqb3);

        }

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder().withQuery(bqb)
                .withFields(EsQueryUtils.getFields(CallHistoryFzjListVo.class))
                .withPageable(PageRequest.of(callHistoryFzjConditionVo.getPage(), callHistoryFzjConditionVo.getPageSize()));
        Page<CallHistoryOld> page = callHistoryOldRepository.search(builder.build());
        Iterator<CallHistoryOld> it = page.iterator();
        while (it.hasNext()) {
            CallHistoryFzjListVo vo = new CallHistoryFzjListVo();
            BeanUtils.copyProperties(it.next(), vo);
            rsList.add(vo);
        }
        return rsList;
    }

    public String saveCallHistoryReturnSessionId(Map map) {
        log.info("=====================[外呼申请]=====================>{}", map);
        CallHistoryOld callHistory = new CallHistoryOld();

        if(StringTools.isNotempty(map.get("sessionId"))){
            String sessionId = map.get("sessionId").toString().trim();
            callHistory.setSessionId(sessionId);
            callHistory.setId(sessionId);
        }


        callHistory.setCallType(StringTools.isNotempty(map.get("callType")) ? map.get("callType").toString() : "-1");
        callHistory.setPageFrom(StringTools.isNotempty(map.get("pageFrom")) ? Integer.valueOf(map.get("pageFrom").toString()) : -1);
        callHistory.setObjectId(StringTools.isNotempty(map.get("objectId")) ? map.get("objectId").toString() : "");
        callHistory.setCreateTime(StringTools.isNotempty(map.get("createTime")) ? new Date(Long.parseLong(map.get("createTime").toString())) : new Date());
        callHistory.setCreateUserId(StringTools.isNotempty(map.get("createUserId")) ? Integer.valueOf(map.get("createUserId").toString()) : -1);
        callHistory.setUnitId(StringTools.isNotempty(map.get("unitId")) ? Integer.valueOf(map.get("unitId").toString()) : -1);
        callHistory.setTeamId(StringTools.isNotempty(map.get("teamId")) ? Integer.valueOf(map.get("teamId").toString()) : -1);
        callHistory.setManagerId(StringTools.isNotempty(map.get("managerId")) ? Integer.valueOf(map.get("managerId").toString()) : -1);
        callHistory.setTopManagerId(StringTools.isNotempty(map.get("topManagerId")) ? Integer.valueOf(map.get("topManagerId").toString()) : -1);
        callHistory.setGroupManagerId(StringTools.isNotempty(map.get("groupManagerId")) ? Integer.valueOf(map.get("groupManagerId").toString()) : -1);
        callHistory.setManagerIds(StringTools.isNotempty(map.get("managerIds")) ? map.get("managerIds").toString() : "");
        callHistory.setCustomerName(StringTools.isNotempty(map.get("customerName")) ? map.get("customerName").toString() : "");
        callHistory.setPhone(StringTools.isNotempty(map.get("phone")) ? map.get("phone").toString() : "");
        callHistory.setRemark(StringTools.isNotempty(map.get("remark")) ? map.get("remark").toString() : "");
        callHistory.setPropertyNo(StringTools.isNotempty(map.get("propertyNo")) ? map.get("propertyNo").toString() : "");
        callHistory.setTotalAddress(StringTools.isNotempty(map.get("totalAddress")) ? map.get("totalAddress").toString() : "");
        callHistory.setCustomerNo(StringTools.isNotempty(map.get("customerNo")) ? map.get("customerNo").toString() : "");
        String res = "";

        res = createCallHistoryReturnSessionId(callHistory);


        return res;
    }

    public String createCallHistoryReturnSessionId(CallHistoryOld callHistory) {
        List<CallHistoryOld> list = new ArrayList<CallHistoryOld>();
        if(StringTools.isEmpty(callHistory.getSessionId())){
            String sessionId = StringTools.getUUID();
            if (callHistory.getPageFrom() == 1) {//手机端联动call
                sessionId = "linkcall_" + sessionId;
            }
            callHistory.setSessionId(sessionId);
            callHistory.setId(sessionId);
        }
        list.add(callHistory);
        boolean flag = insert(callHistory);
        if (flag) {
            return callHistory.getSessionId();
        }
        return "";
    }


    /**
     * 获取云呼记录
     *
     * @param map
     * @return
     */
    public String getCallhistory(Map map) {
        log.info("=====================[云呼记录查询]=====================>{}", map);
        Long start = new Date().getTime();
        CallHistoryZyConditionVo callHistoryConditionVo = new CallHistoryZyConditionVo();
        callHistoryConditionVo.setPageFrom(StringTools.isNotempty(map.get("pageFrom")) ? Integer.valueOf(map.get("pageFrom").toString()) : null);
        callHistoryConditionVo.setPageFroms(StringTools.isNotempty(map.get("pageFroms")) ? map.get("pageFroms").toString().trim() : null);
        callHistoryConditionVo.setObjectId(StringTools.isNotempty(map.get("objectId")) ? Integer.valueOf(map.get("objectId").toString()) : null);
        callHistoryConditionVo.setPageNum(StringTools.isNotempty(map.get("pageNum")) ? Integer.valueOf(map.get("pageNum").toString()) : 0);
        callHistoryConditionVo.setPageSize(StringTools.isNotempty(map.get("pageSize")) ? Integer.valueOf(map.get("pageSize").toString()) : 10);
        callHistoryConditionVo.setSessionId(StringTools.isNotempty(map.get("sessionId")) ? map.get("sessionId").toString() : "");
        callHistoryConditionVo.setUserIds(StringTools.isNotempty(map.get("userIds")) ? map.get("userIds").toString() : "");
        callHistoryConditionVo.setCurrentUserId(StringTools.isNotempty(map.get("currentUserId")) ? Integer.valueOf(map.get("currentUserId").toString()) : null);
        callHistoryConditionVo.setStartCreateTime(StringTools.isNotempty(map.get("startCreateTime")) ? Long.valueOf(map.get("startCreateTime").toString()) : null);
        callHistoryConditionVo.setEndCreateTime(StringTools.isNotempty(map.get("endCreateTime")) ? Long.valueOf(map.get("endCreateTime").toString()) : null);
        callHistoryConditionVo.setCustomerFollowFeedBack(StringTools.isNotempty(map.get("customerFollowFeedBack")) ? map.get("customerFollowFeedBack").toString() : null);
        callHistoryConditionVo.setIsQueryRecordLength(StringTools.isNotempty(map.get("isQueryRecordLength")) ? map.get("isQueryRecordLength").toString() : "0");
        callHistoryConditionVo.setMaxTargetCallLength(StringTools.isNotempty(map.get("maxTargetCallLength")) ? Integer.valueOf(map.get("maxTargetCallLength").toString()) : null);
        callHistoryConditionVo.setMinTargetCallLength(StringTools.isNotempty(map.get("minTargetCallLength")) ? Integer.valueOf(map.get("minTargetCallLength").toString()) : null);
        callHistoryConditionVo.setPageFromType(StringTools.isNotempty(map.get("pageFromType")) ? map.get("pageFromType").toString() : "");
        List<CallHistoryZyListVo> list = getCallhistoryListByZyConditionVo(callHistoryConditionVo);
        Long end = new Date().getTime();
        log.info("========云呼记录查询耗时=========>[{}]毫秒", (end - start));
        return JSON.toJSONString(list);
    }

    public List<CallHistoryZyListVo> getCallhistoryListByZyConditionVo(CallHistoryZyConditionVo conditionVo) {

        List<CallHistoryZyListVo> rsList = new ArrayList<CallHistoryZyListVo>();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        bqb.must(EsQueryUtils.termQuery("isHideRecord","false"));


        if(StringTools.isNotempty(conditionVo.getSessionId())){
            String [] list = conditionVo.getSessionId().split(",");
            if(list.length > 0) {
                BoolQueryBuilder bqbSessionId = QueryBuilders.boolQuery();
                for (int i = 0; i < list.length; i++) {
                    if (StringTools.isNotempty(list[i])) {
                        bqbSessionId.should(EsQueryUtils.termQuery("sessionId", list[i]));
                    }
                }
                bqb.must(bqbSessionId);
            }
        }

        if(StringTools.isNotempty(conditionVo.getPageFromType())){
            BoolQueryBuilder bqbPageFromType = QueryBuilders.boolQuery();
            switch (conditionVo.getPageFromType().trim()){
                case "PC":
                    bqbPageFromType.should(EsQueryUtils.termQuery("pageFrom",2));
                    bqbPageFromType.should(EsQueryUtils.termQuery("pageFrom",0));
                    bqb.must(bqbPageFromType);
//                    stringBuffer.append(" and (\"page_from\" = '2' or \"page_from\" = '0')");
                    break;
                case "CE":
                    bqbPageFromType.should(EsQueryUtils.termQuery("pageFrom",4));
                    bqbPageFromType.should(EsQueryUtils.termQuery("pageFrom",7));
                    bqbPageFromType.should(EsQueryUtils.termQuery("pageFrom",55));
                    bqb.must(bqbPageFromType);
//                    stringBuffer.append(" and (\"page_from\" = '4' or \"page_from\" = '7' or \"page_from\" = '55')");
                    break;
                default:
                    break;
            }
        } else if(StringTools.isNotempty(conditionVo.getPageFrom())){
            BoolQueryBuilder bqbPageFrom = QueryBuilders.boolQuery();
            if(conditionVo.getPageFrom() == 4){
                bqbPageFrom.should(EsQueryUtils.termQuery("pageFrom",conditionVo.getPageFrom()));
                bqbPageFrom.should(EsQueryUtils.termQuery("pageFrom",55));
                bqb.must(bqbPageFrom);
//                stringBuffer.append(" and (\"page_from\" = '"+conditionVo.getPageFrom()+"' or \"page_from\" = '55')");
            } if(conditionVo.getPageFrom() == 2){
                bqbPageFrom.should(EsQueryUtils.termQuery("pageFrom",conditionVo.getPageFrom()));
                bqbPageFrom.should(EsQueryUtils.termQuery("pageFrom",0));
                bqb.must(bqbPageFrom);
//                stringBuffer.append(" and (\"page_from\" = '"+conditionVo.getPageFrom()+"' or \"page_from\" = '0')");
            } else {
                bqb.must(EsQueryUtils.termQuery("pageFrom",conditionVo.getPageFrom()));
//                stringBuffer.append(" and \"page_from\" = '"+conditionVo.getPageFrom()+"'");
            }
        }

        if(conditionVo.getIsQueryRecordLength().equals("1")){//判断是否过滤录音时长
            BoolQueryBuilder bqbIsQueryRecordLength = QueryBuilders.boolQuery();
            bqbIsQueryRecordLength.should(EsQueryUtils.rangeQuery("targetCallLength",0,null,false,false));
            bqbIsQueryRecordLength.should(EsQueryUtils.rangeQuery("recordTimeLength",0,null,false,false));
            bqb.must(EsQueryUtils.existsQuery("targetCallAnsweredTime"));
            bqb.must(bqbIsQueryRecordLength);
//            stringBuffer.append(" and \"target_call_answered_time\" is not null and (\"target_call_length\" > 0 or \"record_time_length\" > 0)");
        }

        if(StringTools.isNotempty(conditionVo.getMinTargetCallLength())){//被叫最大通话时长
            BoolQueryBuilder bqbMinTargetCallLength = QueryBuilders.boolQuery();
            bqbMinTargetCallLength.should(EsQueryUtils.rangeQuery("targetCallLength",conditionVo.getMinTargetCallLength(),null,true,true));
            bqbMinTargetCallLength.should(EsQueryUtils.rangeQuery("recordTimeLength",conditionVo.getMinTargetCallLength(),null,true,true));
            bqb.must(bqbMinTargetCallLength);
//            stringBuffer.append(" and (\"target_call_length\" >= "+conditionVo.getMinTargetCallLength()+" or \"record_time_length\" >= "+conditionVo.getMinTargetCallLength()+")");
        }

        if(StringTools.isNotempty(conditionVo.getMaxTargetCallLength())){//被叫最大通话时长
            BoolQueryBuilder bqbMaxTargetCallLength = QueryBuilders.boolQuery();
            bqbMaxTargetCallLength.should(EsQueryUtils.rangeQuery("targetCallLength",null,conditionVo.getMaxTargetCallLength(),true,true));
            bqbMaxTargetCallLength.should(EsQueryUtils.rangeQuery("recordTimeLength",null,conditionVo.getMaxTargetCallLength(),true,true));
            bqb.must(bqbMaxTargetCallLength);
//            stringBuffer.append(" and (\"target_call_length\" <= "+conditionVo.getMaxTargetCallLength()+" or \"record_time_length\" <= "+conditionVo.getMaxTargetCallLength()+")");
        }

        if(StringTools.isNotempty(conditionVo.getObjectId())){
            bqb.must(EsQueryUtils.termQuery("objectId",conditionVo.getObjectId()));
//            stringBuffer.append(" and \"object_id\" = '"+conditionVo.getObjectId()+"'");
        }

        if(StringTools.isNotempty(conditionVo.getUserIds())){
            /*BoolQueryBuilder bqbUserIds = EsQueryUtils.splitStrInValues(conditionVo.getUserIds(),"createUserId","Integer");
            if(bqbUserIds != null){
                bqb.must(bqbUserIds);
            }*/
            //stringBuffer.append(" and \"create_user_id\" in '"+conditionVo.getUserId()+"'");
            String[] strs = conditionVo.getUserIds().trim().split(",");
            if(strs.length > 0) {
                bqb.must(EsQueryUtils.termsQueryStr2Long("createUserId", strs));

            }
        }

        if(StringTools.isNotempty(conditionVo.getPageFroms())) {
            String[] pageFroms = conditionVo.getPageFroms().split(",");
            if(pageFroms.length > 0) {
                bqb.must(EsQueryUtils.termsQueryStr2Long("pageFrom", pageFroms));
            }
        }

        if(StringTools.isNotempty(conditionVo.getEndCreateTime())){
            bqb.must(EsQueryUtils.rangeQuery("createTime",null,new Date(conditionVo.getEndCreateTime()),true,true));
            /*Long end = 99999999999999l - Long.valueOf(DateUtils.date2DateTimeString2(new Date(conditionVo.getEndCreateTime())));
            stringBuffer.append(" and \"create_time_asc\" >= " + end);*/
        }

        if(StringTools.isNotempty(conditionVo.getStartCreateTime())){
            bqb.must(EsQueryUtils.rangeQuery("createTime",new Date(conditionVo.getStartCreateTime()),null,true,true));
            //Long start = Long.MAX_VALUE - conditionVo.getStartCreateTime();
            /*Long start = 99999999999999l - Long.valueOf(DateUtils.date2DateTimeString2(new Date(conditionVo.getStartCreateTime())));
            stringBuffer.append(" and \"create_time_asc\" <= " + start);*/
        }

        if(StringTools.isNotempty(conditionVo.getCustomerFollowFeedBack())){
            bqb.must(EsQueryUtils.termQuery("customerFollowFeedBack",conditionVo.getCustomerFollowFeedBack()));
//            stringBuffer.append(" and \"customer_follow_feed_back\" = '" +conditionVo.getCustomerFollowFeedBack()+ "'");
        }

        FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder().withQuery(bqb).withSort(fieldSortBuilder).withPageable(PageRequest.of(conditionVo.getPageNum(), conditionVo.getPageSize()));
        Page<CallHistoryOld> page = callHistoryOldRepository.search(builder.build());

        Iterator<CallHistoryOld> it = page.iterator();
        while (it.hasNext()){
            CallHistoryOld item = it.next();
            if(item != null) {
                CallHistoryZyListVo vo = new CallHistoryZyListVo();
                BeanUtils.copyProperties(item, vo);
                /*if (StringTools.isNotempty(vo.getRecordFileUrl())) {
                    boolean existsRecord = callhistoryPlayRecordBiz.existsById(conditionVo.getCurrentUserId() + "-" + item.getSessionId());
                    if(existsRecord){
                        //是否已听录音
                        vo.setIsPlay("true");
                    }
                }*/
                rsList.add(vo);
            }
        }
        return rsList;
    }

    public boolean updateCloudCallBySessionId(Map map) {

        boolean flag = false;

        try {
            String sessionId = map.get("SESSION_ID").toString().trim();
            String createUserId = map.get("CREATE_USER_ID").toString().trim();
            if(StringTools.isEmpty(sessionId) || StringTools.isEmpty(createUserId)){
                log.error("updateCloudCallBySessionId sessinId:{},createUserId:{}",sessionId,createUserId);
                return flag;
            }
            CallHistoryOld callHistory = new CallHistoryOld();
            callHistory.setSessionId(sessionId);
            callHistory.setCreateUserId(Integer.parseInt(createUserId));
            callHistory.setId(sessionId);

            if(StringTools.isNotempty(map.get("PAGE_FROM"))){
                callHistory.setPageFrom(Integer.parseInt(map.get("PAGE_FROM").toString().trim()));
            }

            if(StringTools.isNotempty(map.get("REMARK"))){
                callHistory.setRemark(map.get("REMARK").toString().trim());
            }

            if(StringTools.isNotempty(map.get("OBJECT_ID"))){
                callHistory.setObjectId(map.get("OBJECT_ID").toString().trim());
            }


            if(StringTools.isNotempty(map.get("CUSTOMER_FOLLOW_FEED_BACK"))){//客户跟进反馈
                callHistory.setCustomerFollowFeedBack(map.get("CUSTOMER_FOLLOW_FEED_BACK").toString().trim());

            }

            if(StringTools.isNotempty(map.get("IS_PUSH_APP"))){//是否在APP显示
                callHistory.setIsPushApp(map.get("IS_PUSH_APP").toString().trim());

            }

            if(StringTools.isNotempty(map.get("IS_HIDE_RECORD"))){//是否隐藏录音文件
                callHistory.setIsHideRecord(map.get("IS_HIDE_RECORD").toString().trim());

            }

            if(StringTools.isNotempty(map.get("VOICE_CONTENT"))){//语言识别内容
                callHistory.setVoiceContent(map.get("VOICE_CONTENT").toString().trim());

            }

            if(StringTools.isNotempty(map.get("FEED_BACK"))){//置业反馈信息
                callHistory.setFeedBack(map.get("FEED_BACK").toString().trim());

            }

            if(StringTools.isNotempty(map.get("IS_CLICK_INTERRUPT_CALL"))){
                callHistory.setIsClickInterruptCall(Integer.parseInt(map.get("IS_CLICK_INTERRUPT_CALL").toString()));
            }

            if(StringTools.isNotempty(map.get("RECOGNITION_MSG"))){
                callHistory.setRecognitionMsg(map.get("RECOGNITION_MSG").toString().trim());
            }

            if(callHistoryOldRepository.existsById(callHistory.getId())) {
                callHistoryOldRepository.updateSomeFieldsOnlyNotNull(callHistory);
            }else {
                insert(callHistory);
            }

            flag = true;
        } catch (Exception e) {
            log.error("更新异常:{}",e);
            log.error("=============更新异常数据:{}",map);
        }

        return flag;
    }

    public boolean updateCloudCalls(List<Map> mapList){

        boolean flag = true;

        try {
            for(int i=0;i<mapList.size();i++) {
                Map map = mapList.get(i);
                Object sessionId = map.get("sessionId");
                if (StringTools.isEmpty(sessionId)) {
                    log.error("updateCloudCalls sessinId为空");
                    return false;
                }
                CallHistoryOld callHistory = new CallHistoryOld();
                callHistory.setSessionId(sessionId.toString().trim());
                callHistory.setId(sessionId.toString().trim());

                if (StringTools.isNotempty(map.get("receiveApprecordFileTime"))) {
                    callHistory.setReceiveApprecordFileTime(DateUtils.getDateByStr(map.get("receiveApprecordFileTime").toString().trim(), DateUtils.DATE_FORMAT_DATETIME));
                }

                if (StringTools.isNotempty(map.get("recordFileUrlA"))) {
                    callHistory.setRecordFileUrlPartA(map.get("recordFileUrlA").toString().trim());
                }

                if (StringTools.isNotempty(map.get("recordFileUrl"))) {
                    callHistory.setRecordFileUrl(map.get("recordFileUrl").toString().trim());
                }

                try {
                    if (callHistoryOldRepository.existsById(callHistory.getId())) {
                        callHistoryOldRepository.updateSomeFieldsOnlyNotNull(callHistory);
                    } else {
                        insert(callHistory);
                    }
                } catch (Exception e1) {
                    log.error("更新异常:{}", e1);
                    log.error("=============updateCloudCalls更新异常,跳过:{}", mapList);
                    flag = false;
                }
            }
        } catch (Exception e) {
            log.error("更新异常:{}",e);
            log.error("=============updateCloudCalls更新异常数据:{}",mapList);
            flag = false;
        }

        return flag;
    }

    public Map queryCallHistory4list(CallHistoryZy4ListRequest request, Integer zyUserId){
        Map rsMap = new HashMap();
        List<CallHistoryZyReportListVo> rsList = new ArrayList<CallHistoryZyReportListVo>();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        Date startDate = request.getStartDate();
        Date endDate = request.getEndDate();
        if(startDate != null || endDate != null) {
            String startDateStr = null;
            String endDateStr = null;
            if(startDate != null){
                startDateStr = DateUtils.toString(startDate,"yyyy-MM-dd HH:mm:ss");
            }
            if(endDate != null){
                endDateStr = DateUtils.toString(endDate,"yyyy-MM-dd HH:mm:ss");
            }
            bqb.must(EsQueryUtils.rangeQuery("createTime",startDateStr  != null ? startDateStr : null, endDateStr != null ? endDateStr : null, true, true));
        }
        if(StringTools.isNotempty(request.getSessionId())) {
            bqb.must(EsQueryUtils.termQuery("sessionId", request.getSessionId().trim()));
        }
        if(StringTools.isNotempty(request.getPropertyNo())) {
            bqb.must(EsQueryUtils.termQuery("propertyNo", request.getPropertyNo().trim()));
        }

        if(StringTools.isNotempty(request.getCustomerNo())) {
            bqb.must(EsQueryUtils.termQuery("customerNo", request.getCustomerNo().trim()));
        }

        if(StringTools.isNotempty(request.getCustomerName())){
            bqb.must(EsQueryUtils.wildcardQuery("customerName","*" + request.getCustomerName().trim() + "*"));
        }

        if(StringTools.isNotempty(request.getCustomerPhone())){
            bqb.must(EsQueryUtils.wildcardQuery("customerPhone","*" + request.getCustomerPhone().trim() + "*"));
        }

        if(StringTools.isNotempty(request.getCallType())){
//            bqb.must(EsQueryUtils.splitStrInValues(request.getCallType().trim(),"callType","String"));
            String[] callTypes = request.getCallType().trim().split(",");
            if(callTypes.length > 0) {
                bqb.must(EsQueryUtils.termsQuery("callType", callTypes));
            }
        }

        if(StringTools.isNotempty(request.getTotalAddress())){
            bqb.must(EsQueryUtils.wildcardQuery("totalAddress","*" + request.getTotalAddress().trim() + "*"));
        }

        if(StringTools.isNotempty(request.getProject())){
            BoolQueryBuilder bqb2 = QueryBuilders.boolQuery();
            bqb2.should(EsQueryUtils.wildcardQuery("project","*" + request.getProject().trim() + "*"));
            bqb2.should(EsQueryUtils.wildcardQuery("remark","*" + request.getProject().trim() + "*"));
            bqb.must(bqb2);
        }

        if(StringTools.isNotempty(request.getCommitTo())){
//            bqb.must(EsQueryUtils.splitStrInValues(request.getCommitTo().trim(),"commitTo","Integer"));
            String[] values =  request.getCommitTo().trim().split(",");
            if(values.length > 0){
                bqb.must(EsQueryUtils.termsQueryStr2Long("commitTo",values));
            }
        }

        if(StringTools.isNotempty(request.getPageFrom())){
            bqb.must(EsQueryUtils.termQuery("pageFrom",request.getPageFrom()));
        }

        if(StringTools.isNotempty(request.getFailedReason())){
            bqb.must(EsQueryUtils.termQuery("failedReason",request.getFailedReason().trim()));
            bqb.must(EsQueryUtils.existsQuery("recordFileUrl"));
        }

        if(StringTools.isNotempty(request.getIsPushApp())){
            bqb.must(EsQueryUtils.termQuery("isPushApp",request.getIsPushApp().trim()));
        }

        if(StringTools.isNotempty(request.getCustomerFollowFeedBack())){
//            bqb.must(EsQueryUtils.splitStrInValues(request.getCustomerFollowFeedBack().trim(),"customerFollowFeedBack","String"));
            String[] values = request.getCustomerFollowFeedBack().trim().split(",");
            if(values.length > 0){
                bqb.must(EsQueryUtils.termsQuery("customerFollowFeedBack",values));
            }
        }

        if(request.getIsClick() != null){
            if(request.getIsClick()){
                QueryBuilder qb1 = EsQueryUtils.nestedQuery("clickUsers",EsQueryUtils.termQuery("clickUsers.clickUserId",zyUserId),ScoreMode.None);
                QueryBuilder qb2= EsQueryUtils.nestedQuery("clickUsers",EsQueryUtils.existsQuery("clickUsers.clickTime"),ScoreMode.None);
                bqb.must(qb1).must(qb2);
            }else {
                QueryBuilder qb1 = EsQueryUtils.nestedQuery("clickUsers",EsQueryUtils.termQuery("clickUsers.clickUserId",zyUserId),ScoreMode.None);
                bqb.mustNot(qb1);
            }
        }

        if(request.getIsCallAnswered() != null){
            if(request.getIsCallAnswered()){
                bqb.must(EsQueryUtils.existsQuery("targetCallAnsweredTime"));
            }else {
                bqb.mustNot(EsQueryUtils.existsQuery("targetCallAnsweredTime"));
            }
        }

        if(request.getLeftSecond() != null || request.getRightSecond() != null){
            Integer left = request.getLeftSecond();
            Integer right = request.getRightSecond();
            bqb.must(EsQueryUtils.rangeQuery("connectTimeSecond",left != null ? left:null,right != null ? right:null,true,true));
        }

        if(StringTools.isNotempty(request.getCreateUserIds())){
//            bqb.must(EsQueryUtils.splitStrInValues(request.getCreateUserIds().trim(),"createUserId","Integer"));
            String[] values = request.getCreateUserIds().trim().split(",");
            if(values.length > 0){
                bqb.must(EsQueryUtils.termsQueryStr2Long("createUserId",values));
            }
        }

        if(StringTools.isNotempty(request.getContent())) {
            BoolQueryBuilder bqb2 = QueryBuilders.boolQuery();
            bqb2.should(EsQueryUtils.wildcardQuery("propertyNo", "*" + request.getContent() + "*"));
            bqb2.should(EsQueryUtils.wildcardQuery("customerName", "*" + request.getContent() + "*"));
            bqb2.should(EsQueryUtils.wildcardQuery("remark", "*" + request.getContent() + "*"));

            bqb.must(bqb2);
        }

        FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder().withQuery(bqb).withSort(fieldSortBuilder).withPageable(PageRequest.of(request.getPage(), request.getPageSize()));
        Page<CallHistoryOld> page = callHistoryOldRepository.search(builder.build());
        Iterator<CallHistoryOld> it = page.iterator();

        while (it.hasNext()) {
            CallHistoryOld item = it.next();
            if(item != null) {
                CallHistoryZyReportListVo vo = new CallHistoryZyReportListVo();
                BeanUtils.copyProperties(item,vo);

                if(item.getPageFrom() != null) {
                    vo.setPageFrom(item.getPageFrom());
                }

                if(item.getMainCallType() != null) {
                    vo.setMainCallType(item.getMainCallType());
                }
                rsList.add(vo);
            }
        }
        rsMap.put("data",rsList);
        rsMap.put("total",page.getTotalElements());
        return rsMap;

    }

    public void updateClickUser(ClickUserRequest clickUserRequest){

        //es原有的数据
        CallHistoryOld callHistoryOldDb = selectById(clickUserRequest.getSessionId());

        if(callHistoryOldDb != null) {
            ClickUser clickUser = new ClickUser();
            clickUser.setClickUserId(clickUserRequest.getClickUserId());
            clickUser.setClickTime(clickUserRequest.getClickTime());
            clickUser.setClickUserName(clickUserRequest.getClickUserName());

            //查原有的clickUserList
            List<ClickUser> clickUserList = callHistoryOldDb.getClickUsers();
            if (clickUserList == null) {
                clickUserList = new ArrayList<ClickUser>();
                callHistoryOldDb.setClickUsers(clickUserList);
                clickUserList.add(clickUser);
            } else {
                //一条记录里面相同clickUserId只会记录一次,找到相同clickUserId的记录替换掉
                boolean exist = false;
                for (int i = 0; i < clickUserList.size(); i++) {
                    if (clickUserList.get(i).getClickUserId().intValue() == clickUser.getClickUserId().intValue()) {
                        exist = true;
                        clickUserList.set(i, clickUser);
                        break;
                    }
                }
                if (!exist) {
                    clickUserList.add(clickUser);
                }
            }
            callHistoryOldRepository.updateSomeFieldsOnlyNotNull(callHistoryOldDb);
        }else {
            log.info("调用updateClickUser,查不到CallHistoryOld，sessionId:" + clickUserRequest.getSessionId());
        }
    }

    public List<CallHistoryOldVo> geCallHistoryCrms(String customerIds,String sessionIds,Integer clickUserId) {

        List<CallHistoryOldVo> rsList = new ArrayList<CallHistoryOldVo>();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        if(StringTools.isNotempty(sessionIds)){
            String[] sessArr = sessionIds.split(",");
            if(sessArr.length > 0) {
                bqb.must(EsQueryUtils.termsQuery("id.keyword", Arrays.asList(sessArr)));
            }
        }

        if(StringTools.isNotempty(customerIds)){
            String[] custArr = customerIds.split(",");
            if(custArr.length > 0) {
                bqb.must(EsQueryUtils.termsQuery("objectId",Arrays.asList(custArr)));
            }
        }

        FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("id.keyword").order(SortOrder.ASC);
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder().withQuery(bqb).withSort(fieldSortBuilder);
        Page<CallHistoryOld> page = callHistoryOldRepository.search(builder.build());
        Iterator<CallHistoryOld> it = page.iterator();

        while (it.hasNext()) {
            CallHistoryOld item = it.next();
            if(item != null) {
                CallHistoryOldVo vo = new CallHistoryOldVo();
                BeanUtils.copyProperties(item,vo);
                if(vo.getPageFrom() != null && vo.getPageFrom().intValue() != -1) {
                    vo.setPageFromDesc(PageFromType.fromStr(vo.getPageFrom() + "").getDesc());
                }
                //是否已听录音
                vo.setIsPlay("F");
                List<ClickUser> clickUserList = item.getClickUsers();
                if(clickUserList != null && clickUserId != null){
                    for(int i=0;i<clickUserList.size();i++) {
                        ClickUser clickUser = clickUserList.get(i);
                        if (clickUser.getClickUserId().intValue() == clickUserId.intValue()) {
                            vo.setIsPlay("T");
                            break;
                        }
                    }
                }
                rsList.add(vo);
            }
        }

        return rsList;
    }
}
